package com.getpebble.android.jskit.bridge;

import android.content.Context;
import android.text.TextUtils;
import com.getpebble.android.common.core.trace.Trace;
import com.getpebble.android.common.framework.install.app.AppBundle;
import com.getpebble.android.common.model.AppInfo;
import com.getpebble.android.jskit.JsInstalledApplicationInfo;
import com.getpebble.android.jskit.webapps.JsKit;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.UUID;
import org.apache.commons.io.IOUtils;

public class JsAppInstaller {
    private static final String TAG = JsAppInstaller.class.getSimpleName();
    protected static JsAppInstaller sInstance;
    protected Context mContext;
    protected File mInstallDir = this.mContext.getDir("jskit_installed_apps", 0);

    protected JsAppInstaller(Context c) {
        this.mContext = c;
        JsAppContextBridge.getInstance().setAppContext(this.mContext);
    }

    public static JsAppInstaller getInstance(Context context) {
        if (sInstance == null) {
            sInstance = new JsAppInstaller(context.getApplicationContext());
        }
        return sInstance;
    }

    public boolean installNewJsAppLocally(AppBundle bundle) {
        if (bundle == null) {
            return false;
        }
        InputStream inputStream;
        String appNameIdentifier = getAppNameIdentifier(bundle);
        String appNameVersionIdentifier = getAppNameVersionIdentifier(bundle);
        try {
            inputStream = bundle.getInputStreamForComponent("pebble-js-app.js");
        } catch (Exception e) {
            Trace.debug(TAG, "installNewJsAppLocally", e);
            inputStream = null;
        }
        if (inputStream == null) {
            return false;
        }
        try {
            if (!installNewSingleFileJsAppLocally(appNameIdentifier, appNameVersionIdentifier, bundle.getInputStreamForComponent("appinfo.json"), inputStream)) {
                return false;
            }
            JsKit.jsKitAccess().rescanForInstalledWebApps();
            return true;
        } catch (IOException e2) {
            Trace.debug(TAG, "installNewJsAppLocally", e2);
            return false;
        }
    }

    private boolean installNewSingleFileJsAppLocally(String appNameIdentifier, String appNameVersionIdentifier, InputStream inputStreamForAppinfoSourceData, InputStream inputStreamForSourceData) throws IOException {
        File targetDir = new File(appDirAbsPathForAppIdentifier(appNameVersionIdentifier));
        if (!targetDir.mkdirs() && !targetDir.isDirectory()) {
            return false;
        }
        OutputStream os = new FileOutputStream(new File(targetDir.getAbsolutePath() + File.separator + "pebble-js-app.js"));
        IOUtils.copy(inputStreamForSourceData, os);
        os.flush();
        os.close();
        os = new FileOutputStream(new File(targetDir.getAbsolutePath() + File.separator + "appinfo.json"));
        IOUtils.copy(inputStreamForAppinfoSourceData, os);
        os.flush();
        os.close();
        return true;
    }

    private String getAppNameVersionIdentifier(AppBundle bundle) {
        AppInfo appInfo = bundle.getAppInfo();
        if (appInfo != null) {
            return appInfo.getLongName() + "__" + appInfo.getVersionCode();
        }
        return null;
    }

    private String getAppNameIdentifier(AppBundle bundle) {
        if (bundle.getAppInfo() != null) {
            return bundle.getAppInfo().getLongName();
        }
        return null;
    }

    public File getInstallDir() {
        return this.mInstallDir;
    }

    public String appDirAbsPathForAppIdentifier(String appNameVersionIdentifier) {
        String str = null;
        if (appNameVersionIdentifier != null) {
            appNameVersionIdentifier = appNameVersionIdentifier.trim();
            if (appNameVersionIdentifier.length() >= 1) {
                String installDirAbsPath = getInstallDir().getAbsolutePath();
                if (installDirAbsPath != null) {
                    try {
                        str = new File(installDirAbsPath + File.separator + safeAppNameIdentifier(appNameVersionIdentifier)).getAbsolutePath();
                    } catch (Exception e) {
                        Trace.debug(TAG, "appDirAbsPathForAppIdentifier", e);
                    }
                }
            }
        }
        return str;
    }

    public static String safeAppNameIdentifier(String appNameVersionIdentifier) {
        return appNameVersionIdentifier.replaceAll("[\t\n\r :*\\/]", "_");
    }

    public void removeOldJsApp(UUID uuid) {
        JsInstalledApplicationInfo installedAppInfo = JsKit.installedWebappsInfoForUuid(uuid);
        if (installedAppInfo == null) {
            Trace.debug(TAG, "removeOldJsApp: installedAppInfo is null");
            return;
        }
        String appDir = installedAppInfo.getInstalledAbsPathOnFilesystem();
        if (!TextUtils.isEmpty(appDir)) {
            boolean appDirRemovedOk = removeJsAppDir(appDir);
            JsKit.jsKitAccess();
            JsKit.signalJsAppDirectoryRemoved(appDir);
        }
    }

    public boolean removeJsAppDir(String appDirName) {
        try {
            return removeEntireDirTree(new File(appDirName));
        } catch (Exception e) {
            Trace.debug(TAG, "removeJsAppDir", e);
            return false;
        }
    }

    private static boolean removeEntireDirTree(File rootDirRemovedInclusively) {
        return removeRecursive(rootDirRemovedInclusively);
    }

    private static boolean removeRecursive(File node) {
        if (node == null) {
            Trace.debug(TAG, "removeRecursive: node is null");
            return false;
        } else if (!node.isDirectory()) {
            return removeFile(node);
        } else {
            File[] fileList = node.listFiles();
            if (fileList != null && fileList.length > 0) {
                for (File nextNode : fileList) {
                    if (!removeRecursive(nextNode)) {
                        return false;
                    }
                }
            }
            return removeEmptyDir(node);
        }
    }

    private static boolean removeFile(File node) {
        boolean z = false;
        if (node == null) {
            Trace.debug(TAG, "removeFile: node is null");
        } else if (!node.isDirectory()) {
            try {
                z = node.delete();
            } catch (Exception e) {
            }
        }
        return z;
    }

    private static boolean removeEmptyDir(File node) {
        boolean z = false;
        if (node == null) {
            Trace.debug(TAG, "removeEmptyDir: node is null");
        } else if (node.isDirectory()) {
            try {
                z = node.delete();
            } catch (Exception e) {
            }
        }
        return z;
    }
}
